#!/usr/bin/python3
import sys
import json
import functools

# part 1

def compare_signals(left, right):
    l_int, r_int = type(left) == int, type(right) == int
    #print(f'comparing\n{left} (int: {l_int}) and\n{right} (int: {r_int})')
    if l_int and r_int:
        return left - right

    if l_int:
        return compare_signals([left], right)

    if r_int:
        return compare_signals(left, [right])

    for i in range(min(len(left), len(right))):
        nested_comparison = compare_signals(left[i], right[i])
        if nested_comparison != 0:
            return nested_comparison

    return len(left) - len(right)

def part1():
    i = 1
    indices = []
    for line in sys.stdin:
        if line == '\n':
            continue
        left = json.loads(line.strip())
        right = json.loads(next(sys.stdin).strip())
        #print('index', i, left, 'and', right)

        print(f'\nchecking signal {i}')
        result = compare_signals(left, right) <= 0
        print(f'signal {i} is in right order: {result}')
        if result:
            indices.append(i)
        i += 1
    print(f'the sum of indices is {sum(indices)}')

# part 2

def part2():
    packets = [[[2]], [[6]]]
    for line in sys.stdin:
        if line == '\n':
            continue
        left = json.loads(line.strip())
        right = json.loads(next(sys.stdin).strip())
        packets.append(left)
        packets.append(right)
    packets.sort(key=functools.cmp_to_key(compare_signals))

    divider_indices = []
    for i, packet in enumerate(packets):
        #print(packet)
        if packet == [[2]] or packet == [[6]]:
            divider_indices.append(i + 1)

    print(f'the divider indices are {divider_indices} (with product {divider_indices[0] * divider_indices[1]})')

if sys.argv[1] in '1':
    part1()
else:
    part2()